package com.zly.bscloud.sort;

import com.csvreader.CsvReader;
import com.zly.bscloud.entity.Garbage;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhouxiaoyu
 * @Date 2020/5/6 8:37
 * @Version 1.0
 */
public class CSVUtil {
    public static char separator = ',';
    /**
     * 读取CSV文件
     *
     */
    public static List<Garbage> readCSV() throws Exception {
        String filePath = "D:/garbage.csv";
        CsvReader reader = null;
        List<Garbage> dataList = new ArrayList<Garbage>();
        try {
            //如果生产文件乱码，windows下用gbk，linux用UTF-8
            reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));

            // 读取表头
            reader.readHeaders();
            //String[] headArray = reader.getHeaders();//获取标题
            //System.out.println(headArray[0] + headArray[1] + headArray[2]);

            // 逐条读取记录，直至读完
            while (reader.readRecord()) {
                // 读一整行
                //System.out.println(reader.getRawRecord());
                // 读这行的第一列
                //System.out.println(reader.get("学号"));
                // 读这行的第二列
                //System.out.println(reader.get(1));

                Garbage garbage = new Garbage();
                garbage.setName(reader.get(0));
                String[] cate={"可回收物","有害垃圾","湿垃圾","干垃圾"};
                if(reader.get(1)!=null){
                    Integer k = Integer.parseInt(reader.get(1).toString().trim());
                    //garbage.setCategory(cate[k-1]);
                }

                dataList.add(garbage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

        return dataList;
    }

}
